package com.yang.token.controller;

import com.yang.token.config.JwtToken;
import com.yang.token.model.Acount;
import com.yang.token.model.User;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.naming.AuthenticationException;
import java.util.*;

@RestController
public class JwtController {

    @Autowired
    private JwtToken jwtToken;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Acount user) {
// 1. 验证用户名和密码
// 2. 验证成功生成token
        System.out.println(user.getUsername() + "  " + user.getPassword());
        if (user.getUsername().equals("yangliang") && user.getPassword().equals("yangliang123")){
            String token = jwtToken.generateToken(user);
            Map<String, Object> msg = new HashMap<String,Object>();
            msg.put("massage", "登录成功");
            msg.put("code", 200);
            msg.put("token", token);
            return msg;
        }

        Map<String, Object> msg = new HashMap<String,Object>();
        msg.put("massage", "登录失败,账号或密码错误");
        msg.put("code", 400);
        msg.put("token", null);
        return msg;
    }

    @GetMapping("/getUserInfo")
    public String getUserInfo(@RequestHeader("token") String token) throws AuthenticationException {
// 黑名单token
        List<String> blacklistToken = Arrays.asList("禁止访问的token");
        Claims claims = jwtToken.getClaimByToken(token);
        if (claims == null || JwtToken.isTokenExpired(claims.getExpiration()) || blacklistToken.contains(token)) {
            throw new AuthenticationException("token 不可用");
        }

       // String userId = claims.getSubject();
// 根据用户id获取接口数据返回接口
        return claims.getSubject();

    }

    @PostMapping("/getUserAll")
    public List<User> getUserAll(@RequestParam(name = "id") String id,
                                 @RequestParam(name = "name") String name,
                                 @RequestParam(name = "birth") String birth,
                                 @RequestParam(name = "sex") String sex){

        System.out.println(id+" "+ " " + name+birth+ " "+ sex);

        List<User> userList = new ArrayList<>();

        for (int i = 1; i <= 10; i++) {
            User u = new User(i, "学生"+i, "$*%&*(*", i*1000);
            userList.add(u);
        }

        return userList;
    }
}
